package com.bwsoft.util;
 
import java.io.IOException;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
 
public class DesUtil {
 
    private static byte[] iv = {1, 2, 3, 4, 5, 6, 7, 8};
     
    /**
     * Description 根据键值进行加密
     * @param data 
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    public static String encrypt(String encryptString, String encryptKey) throws Exception {

	      

	       IvParameterSpec zeroIv =new IvParameterSpec(iv);

	       SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");

	       Cipher cipher =Cipher.getInstance("DES/CBC/PKCS5Padding");

	       cipher.init(Cipher.ENCRYPT_MODE,key, zeroIv);

	       byte[] encryptedData =cipher.doFinal(encryptString.getBytes("UTF-8"));

	       
	       return Base64Util.getBase64(encryptedData);
    }
 
    /**
     * Description 根据键值进行解密
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String decrypt(String str, String decryptKey) throws IOException,
            Exception {
    		byte[] encryptedData=Base64Util.getByteFromStringByBase64(str);

	       IvParameterSpec zeroIv =new IvParameterSpec(iv);

	       SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes("UTF-8"), "DES");

	       Cipher cipher =Cipher.getInstance("DES/CBC/PKCS5Padding");

	       cipher.init(Cipher.DECRYPT_MODE,key, zeroIv);

	       byte decryptedData[] =cipher.doFinal(encryptedData);

	       String decryptedString =new String(decryptedData, "UTF-8");
	      
	       return decryptedString;

    }
}
 
